
package com.ifcar.app.view;

import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.Gallery;

import com.ifcar.app.activity.MyApplication;
import com.ifcar.app.activity.VoteSubmit;
import com.ifcar.app.adapter.VoteWithTabAdapter;
import com.ifcar.app.bean.VoteBean;
import com.ifcar.app.db.NewsSQLiteOpenHelper;
import com.ifcar.app.util.StringUtil;
import com.ifcar.app.util.ThemeSettingsHelper;
import com.ifcar.app.activity.R;

public class VoteGallery extends FrameLayout implements OnItemSelectedListener {

	/**
     * Gallery
     */
    private MyGallery mGallery;

    /**
     * 指示器
     */
    private VoteDotIndicator mIndicator;
    private VoteWithTabAdapter  mAdapter;

    private Button mVoteButton;
    
    private Context mContext;
    
    private ThemeSettingsHelper themeSettingsHelper;
    
    public VoteGallery(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public VoteGallery(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public VoteGallery(Context context) {
        super(context);
    }

    @Override
    protected void onFinishInflate() {
    	super.onFinishInflate();
    	mContext = getContext();
    	mGallery = (MyGallery) findViewById(R.id.my_vote_gallery);
        mGallery.setAutoRun(0);
        mGallery.setOnItemSelectedListener(this);

        mIndicator = (VoteDotIndicator) findViewById(R.id.vote_indicator);
        mVoteButton = (Button) findViewById(R.id.vote_do);
        
		themeSettingsHelper = ThemeSettingsHelper.getThemeSettingsHelper(mContext);
    }

    public Gallery getGallery() {
        return mGallery;
    }
    
    public void setAdapter(VoteWithTabAdapter adapter) {
        mAdapter = adapter;
        mGallery.setAdapter(adapter);
        if (adapter != null) {
            mGallery.setSelection(mAdapter.getInitPosition(0));
        }
    }
    
    public void setOnItemClickListener(OnItemClickListener listener) {
        mGallery.setOnItemClickListener(listener);
    }
    
    @Override
    public void onItemSelected(AdapterView<?> adapter, View arg1, int position, long arg3) {
        final int count = mAdapter.getRealCount();        
        final int realPosition = mAdapter.getRealPosition(position);
        if (mIndicator.getTotalItems() != count) {
            mIndicator.setTotalItems(count);
        }
        mIndicator.setCurrentItem(realPosition);
        
        updateDisplay(realPosition);
//        Runnable r = new Runnable() {            
//            @Override
//            public void run() {
//                updateDisplay(realPosition);                
//            }
//        };
//        mGallery.setXXXRunnalbe(r);
        
    }
    
    private Map<String, Object> map ;
    public void updateDisplay(int position) {
    	map = null;
    	map = (Map<String, Object>) mAdapter.getItem(position);
    	
    	if(null == map) return;
    	
    	String voteId = "" + map.get(StringUtil.VOTE_ID);
    	mVoteButton.setTag(voteId);
    	MyApplication app = (MyApplication)mContext.getApplicationContext();
    	SQLiteDatabase db = app.getSQLiteDatabase();
		Cursor cur = db.query(NewsSQLiteOpenHelper.VOTE_TABLE, new String[]{NewsSQLiteOpenHelper.VOTE_ID},
				NewsSQLiteOpenHelper.VOTE_ID + "=" + voteId, null, null, null, NewsSQLiteOpenHelper.VOTE_AUTO_ID + " desc");

		int flag = cur.getCount();
		cur.close();
		
		if(0 == position){
			if(flag>0){
				setSeeListener();
			}else{
				mVoteButton.setText(mContext.getResources().getString(R.string.vote_submit));
				mVoteButton.setOnClickListener(voteDoListener);
				themeSettingsHelper.setViewBackgroud(mContext, mVoteButton, R.drawable.netease_big_button);
		    	themeSettingsHelper.setTextViewColor(mContext, mVoteButton, R.color.list_title_color);
			}
		}else{
			setSeeListener();
		}
		
    }
    
    private void setSeeListener(){
    	mVoteButton.setText(mContext.getResources().getString(R.string.vote_see));
		mVoteButton.setOnClickListener(voteSeeListener);
		themeSettingsHelper.setViewBackgroud(mContext, mVoteButton, R.drawable.netease_big_button);
    	themeSettingsHelper.setTextViewColor(mContext, mVoteButton, R.color.list_title_color);
    }

    /**
	 * 查看投票
	 */	
	public View.OnClickListener voteSeeListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			
			/**
			 * 查看投票
			 */
			MyApplication app = (MyApplication)mContext.getApplicationContext();
			
			if(!app.isKeyback()){
				v.setEnabled(false);
				seeVoteResult();
			}
		}
	};
	
	/**
	 * 查看投票
	 */
	protected void seeVoteResult() {
		isDoSubmit = false;
		Intent intent = new Intent(mContext, VoteSubmit.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Bundle b = new Bundle();
		VoteBean vb = new VoteBean();
		
		vb.setId((String)map.get(StringUtil.VOTE_ID));
		vb.setItemLsit((List<Map<String,Object>>)map.get(StringUtil.VOTE_ITEM_LIST));
		vb.setItemQuestion((String)map.get(StringUtil.VOTE_QUESTION));
		
		b.putSerializable("votebean", vb);
		b.putInt(StringUtil.ALREADY_VOTE, 1);
		intent.putExtra("vb", b);
		mContext.startActivity(intent);
	}
	
	/**
	 * 投票监听
	 */
	public View.OnClickListener voteDoListener = new View.OnClickListener() {
		@SuppressWarnings("unchecked")
		@Override
		public void onClick(View v) {
		
			MyApplication app = (MyApplication)mContext.getApplicationContext();
			
			if(!app.isKeyback()){
				v.setEnabled(false);
		    	SQLiteDatabase db = app.getSQLiteDatabase();
		    	
				Cursor cur = db.query(NewsSQLiteOpenHelper.VOTE_TABLE, new String[]{NewsSQLiteOpenHelper.VOTE_ID},
						NewsSQLiteOpenHelper.VOTE_ID + "=" + map.get(StringUtil.VOTE_ID), null, null, null, NewsSQLiteOpenHelper.VOTE_AUTO_ID + " desc");
				int num = cur.getCount();
				cur.close();
				if(num>0){
					/**
					 * 查看投票
					 */
					seeVoteResult();
					
				}else{
					Intent intent = new Intent(mContext, VoteSubmit.class);
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					Bundle b = new Bundle();
					VoteBean vb = new VoteBean();
					
					vb.setId((String)map.get(StringUtil.VOTE_ID));
					vb.setItemLsit((List<Map<String,Object>>)map.get(StringUtil.VOTE_ITEM_LIST));
					vb.setItemQuestion((String)map.get(StringUtil.VOTE_QUESTION));
					
					b.putSerializable("votebean", vb);
					
					intent.putExtra("vb", b);
					mContext.startActivity(intent);
					isDoSubmit = true;
				}
			}
			
		}
	};
    
	private boolean isDoSubmit = false;
	public boolean isDoSubmit(){
		return isDoSubmit;
	}
	
    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
    }

    public void startAutoScroll(boolean autoScroll) {
        if (mGallery != null) {
            mGallery.startAutoScroll(autoScroll);
        }
    }
    
    public void setIndicator(Context context, ThemeSettingsHelper themeSettingsHelper) {
		// TODO Auto-generated method stub
    	mIndicator.setIndicatorBg(context, themeSettingsHelper);
    	
		themeSettingsHelper.setViewBackgroud(mContext, mVoteButton, R.drawable.netease_big_button);
    	themeSettingsHelper.setTextViewColor(mContext, mVoteButton, R.color.list_title_color);
    	
//    	if (mTag.getTag() != null) {
//    	    Integer position = (Integer)mTag.getTag();
//    	    updateTag(position);
//    	}
    	
//    	themeSettingsHelper.setViewBackgroud(context, mTag, R.drawable.subject_bk);
//        themeSettingsHelper.setTextViewColor(context, mTag, R.color.list_tag_color);
	}

    // TODO ...
    // @Override
    // protected void onVisibilityChanged(View changedView, int visibility) {
    // super.onVisibilityChanged(changedView, visibility);
    // if (visibility != VISIBLE || getWindowVisibility() != VISIBLE && mGallery
    // != null
    // && mAdapter != null) {
    // if (mAdapter.getCount() > 0) {
    // mGallery.setSelection(mAdapter.getInitPosition(mGallery.getSelectedItemPosition()));
    // }
    // }
    // }

    @Override
    protected void onWindowVisibilityChanged(int visibility) {
        super.onWindowVisibilityChanged(visibility);
        if (visibility != VISIBLE || !isShown() && mGallery != null && mAdapter != null) {
            if (null != mAdapter && mAdapter.getCount() > 0) {
                mGallery.setSelection(mAdapter.getInitPosition(mGallery.getSelectedItemPosition()));
            }
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (mGallery != null && mAdapter != null) {
            if (mAdapter.getCount() > 0) {
                mGallery.setSelection(mAdapter.getInitPosition(mGallery.getSelectedItemPosition()));
            }
        }
    }
    
}
